<!-- 需求详情 -->
<template>
	<loading-page v-if="data.loading" />
	<template v-else-if="!data.loading&&showDetail">
		<!-- 步骤 -->
		<view class="steps">
			<steps :list="data.steps" active="-1" :small-point="true" borderColor="#fff" lineColor="#fff" textColor="#fff" descColor="#fff" />
		</view>
		<!-- 基本信息 -->
		<view class="infos">
			<view class="title">
				<text>{{data.infos.title}}</text>
			</view>
			<view class="tags">
				<view :class="['item state','item-task-status'+data.infos.task_status]" v-if="data.infos.check_status==2">{{taskStatus(data.infos.task_status)}}</view>
				<view :class="['item state','item-check-status'+data.infos.check_status]" v-if="data.publisher.yes">{{checkStatus(data.infos.check_status)}}</view>
				<view class="item time">
					<icon class="iconfont icon">&#xe813;</icon>
					<text>{{data.infos.deadline}} 截止</text>
				</view>
			</view>
			<view class="price">
				<text class="unit">¥</text>
				<text class="value">{{data.infos.price}}</text>
			</view>
			<view class="date">
				<text>{{data.infos.publisher_nickname}} &nbsp;&nbsp;<template v-if="data.infos.check_status==2">{{data.infos.check_time}}发布</template></text>
			</view>
		</view>
		<!-- 需求详情描述 -->
		<view class="detail">
			<view class="hd">
				<text>悬赏描述</text>
			</view>
			<view class="bd">
				<text>{{data.infos.description}}</text>
			</view>
		</view>
		<!-- 接单大牛 -->
		<view class="list" v-if="showTakeOrders">
			<view class="hd">
				<text>接单大牛</text>
			</view>
			<view class="bd">
				<view class="tab">
					<tabs :list="data.tabList" @change="merchant.changeTab" />
				</view>
				<view class="order">
					<template v-for="(item,index) in takeOrders" :key="index" v-if="takeOrders.length">
						<order-item :index="index" :item="item" :pick="data.publisher.pick" :checked="item.checked" :selected="item.is_winner" @changePick="publisher.changePick" />
					</template>
					<template v-else>
						<order-item-empty :publisher="data.publisher.yes" :tabValue="data.tabValue" />
					</template>
				</view>
			</view>
		</view>
		<!-- 滑到底部操作 -->
		<template v-if="data.publisher.yes">
			<view class="foot">
				<view class="handle" v-if="data.infos.check_status==2&&data.infos.task_status==1">
					<text class="msg">不再需要？您可以手动</text>
					<text class="btn btn-text" @click="publisher.closeTask()">关闭悬赏</text>
				</view>
			</view>
		</template>
		<template v-if="showMoreTip">
			<view class="foot">
				<view class="handle">
					<text class="msg">仅支持查看以上大牛，查看更多请 </text>
					<navigator class="btn btn-text" url="/pages/find/find" open-type="switchTab" :hover-stop-propagation="true">点击这里</navigator>
				</view>
			</view>
		</template>
		<!-- 底部操作 -->
		<template v-if="data.publisher.yes">
			<view class="operate" v-if="data.infos.check_status==3">
				<button type="default" class="btn btn-one" hover-class="btnClickStyle" @click="publisher.edit()">
					<text>去修改</text>
				</button>
			</view>
			<view :class="['operate',{'operate-two':data.publisher.pick}]" v-if="showPickHandle">
				<template v-if="data.publisher.pick">
					<button type="default" class="btn small small-font32" hover-class="btnClickStyle" @click="publisher.pickCancel()">
						<text>取消</text>
					</button>
					<button type="default" :class="['btn',{'btn-dis':disabledPickConfirm}]" :disabled="disabledPickConfirm" hover-class="btnClickStyle" @click="publisher.pickConfirm()">
						<text>确认选择</text>
					</button>
				</template>
				<template v-else>
					<button type="default" class="btn btn-one" hover-class="btnClickStyle" @click="publisher.pick()">
						<text>选人</text>
					</button>
				</template>
			</view>
		</template>
		<template v-else>
			<template v-if="data.infos.task_status==1">
				<!-- 未抢单 -->
				<view class="operate operate-two" v-if="data.merchant.info.takeorders==0">
					<button type="default" class="btn small" hover-class="btnClickStyle" @click="merchant.toIm()">
						<icon class="iconfont icon">&#xe78f;</icon>
						<text>聊一聊</text>
					</button>
					<button type="default" class="btn" hover-class="btnClickStyle" @click="merchant.getOrder()">申请接单</button>
				</view>
				<!-- 已抢单 -->
				<view class="operate operate-two" v-else-if="data.merchant.info.takeorders==1">
					<button type="default" class="btn small" hover-class="btnClickStyle" @click="merchant.toIm()">
						<icon class="iconfont icon">&#xe78f;</icon>
						<text>聊一聊</text>
					</button>
					<button type="default" class="btn" hover-class="btnClickStyle" @click="merchant.contact()">您已申请，点击获取手机号</button>
				</view>
			</template>
		</template>
	</template>
	<!-- 被截胡 -->
	<template v-else>
		<empty msg="该悬赏已经被截胡啦~" />
	</template>
	<!-- 联系 -->
	<popup-contact ref="popupContactRef"></popup-contact>
	<!-- 登录组件 -->
	<weixin-login ref="wxLogin" @loginSuccess="checkVisitorStatus" />
</template>
<script setup>
	import { ref, reactive, computed, defineComponent } from 'vue';
	import { onLoad, onReady, onReachBottom } from '@dcloudio/uni-app';
	import tabs from './components/tabs.vue';
	import orderItem from './components/order-item.vue';
	import orderItemEmpty from './components/order-item-empty.vue';
	import popupContact from '@/pages/find/components/popup-contact.vue';
	import { getDetail, userFinishTask, userSelectMerchant } from '@/subpages/common/api/task/detail.js';
	import { getPublisherMobile } from '@/subpages/common/api/task/detail.merchant.js';
	import { editPhoneNumber } from '@/subpages/common/api/set.js';
	import useGetList from '@/common/hooks/useGetList.js';
	import useStatus from '@/common/hooks/useStatus.js';
	import { deepClone } from '@/common/utils/index.js';
	import { useStore } from 'vuex';
	import { showModal } from '@/common/hooks/useShow.js';
	import config from '@/uni.config.js';
	defineComponent({
		tabs,
		orderItem,
		orderItemEmpty,
		popupContact
	});
	onLoad((options) => {
		data.options = options;
		data.taskid = options.id;
		checkVisitorStatus();
	});
	onReady(() => {
		data.lineAnimation = true;
	});
	onReachBottom(() => {
		if (data.publisher.yes) reachBottom();
	});
	uni.$on('GOAUTH', () => {
		setTimeout(() => {
			goAuth();
		}, 200)
	});
	const popupContactRef = ref(null);
	const wxLogin = ref(null);
	const store = useStore();
	const TASK_STATUS = {
		// 审核状态
		check: {
			reviewing: 1, //审核中
			reviewSuccess: 2, //审核成功
			reviewFail: 3 //审核失败
		},
		// 任务状态
		task: {
			ongoing: 1, //进行中
			completed: 2, //已完成
			closed: [31, 32] //已关闭（发布者/管理员关闭）
		}
	};
	const data = reactive({
		loading: true,
		type: 0,
		options: {},
		taskid: '',
		publisher: { // 关于发布者对象的信息
			yes: 0, //是否是发布者
			pick: 0 //是否选人状态
		},
		merchant: { //关于商人对象的信息
			yes: 0,
			info: null
		},
		takeordersIinfos: {},
		searchParams: {
			is_winner: 'all'
		},
		steps: [],
		tabValue: 'all',
		tabList: [],
		lineAnimation: false,
		infos: null,
		orders: []
	});
	const { getDataList, dataList, loadMore, reachBottom } = useGetList();
	const { navToCheckLogin, goAuth, toIm } = useStatus(wxLogin);
	// 判断访问者的身份：发布者/非发布者
	function checkVisitorStatus() {
		const isPublisher = data.options.mid == store.getters.userInfo.mid;
		data.publisher.yes = isPublisher;
		data.merchant.yes = !isPublisher;
		if (data.publisher.yes) { //发布者
			publisher.init();
		} else { //商户
			merchant.init();
		}
	}
	// 发布者（自己进自己的详情页）
	const publisher = {
		init() {
			data.steps = [{
				name: '登记',
				desc: '审核发布'
			}, {
				name: '沟通',
				desc: '深入洽谈'
			}, {
				name: '选人',
				desc: '确定接单'
			}, {
				name: '执行',
				desc: '实现需求'
			}, {
				name: '完成',
				desc: '支付报酬'
			}];
			data.searchParams = {
				taskid: data.taskid,
				is_winner: 'all'
			}
			this.bind();
		},
		async bind() {
			try {
				const res = await getDataList({
					url: '/crm/task/myPublishTaskdetail',
					params: {
						...data.searchParams
					},
					key: 'takeorders_infos.takeorders',
					showLoading: false
				});
				data.infos = res.task_infos;
				data.tabList = [{ name: '所有抢单', value: 'all', num: (+res.takeorders_infos.nowin_num) + (+res.takeorders_infos.winner_num) }, { name: '选中', value: 1, num: +res.takeorders_infos.winner_num }, { name: '未选中', value: 0, num: +res.takeorders_infos.nowin_num }];
			} catch (e) {}
			data.loading = false;
		},
		// 审核失败-去修改
		edit() {
			uni.navigateTo({
				url: `/subpages/task/add/add?type=edit&item=${encodeURIComponent(JSON.stringify(data.infos))}`,
				events: {
					acceptDataFromOpenedPage(res) {
						if (data.publisher.yes) {
							publisher.init();
						}
					}
				}
			})
		},
		// 关闭需求
		closeTask() {
			let that = this;
			uni.showModal({
				title: '提示',
				content: '确定要关闭？',
				confirmColor: '#E1835B',
				cancelColor: '#aaa',
				cancelText: '确认',
				confirmText: '取消',
				success(res) {
					if (res.cancel) {
						that.closeTaskReq();
						uni.$emit('CLOSETASK');
					}
				}
			})
		},
		// 关闭需求请求
		async closeTaskReq() {
			await userFinishTask({ taskid: data.taskid });
			publisher.init();
		},
		// 选人
		pick() {
			data.publisher.pick = 1;
		},
		// 改变选人
		changePick(mid) {
			dataList.value.forEach(item => {
				item.checked = item.merchant_mid === mid;
			});
		},
		// 取消选人
		pickCancel() {
			data.publisher.pick = 0;
			dataList.value.forEach(item => {
				item.checked = false;
			});
		},
		// 确认选人
		async pickConfirm() {
			const confirmPicks = takeOrders.value.filter(item => item.checked);
			showModal({
				content: '确定接受该大牛的接单申请？',
				confirmColor: '#E1835B',
				cancelColor: '#aaa',
				confirm() {
					userSelectMerchant({
						taskid: data.taskid,
						merchant_mid: confirmPicks[0].merchant_mid
					}).then(res => {
						publisher.init();
						publisher.pickCancel();
					})
				}
			})
		}
	}
	// 商户
	const merchant = {
		init() {
			data.steps = [{
				name: '申请',
				desc: '提交资料'
			}, {
				name: '沟通',
				desc: '具体了解'
			}, {
				name: '选人',
				desc: '确定接单'
			}, {
				name: '执行',
				desc: '实现需求'
			}, {
				name: '完成',
				desc: '获得报酬'
			}];
			data.searchParams = {
				taskid: data.taskid,
				is_winner: 'all'
			}
			this.bind();
		},
		async bind(showLoading = false) {
			try {
				const res = await getDataList({
					url: '/crm/task/taskdetail',
					params: {
						...data.searchParams
					},
					key: 'takeorders_infos.takeorders',
					showLoading: showLoading
				});
				data.infos = res.task_infos;
				data.merchant.info = res.merchant_takeorders_info;
				data.takeordersIinfos = res.takeorders_infos;
				data.tabList = [{ name: '所有抢单', value: 'all', num: (+res.takeorders_infos.nowin_num) + (+res.takeorders_infos.winner_num) }, { name: '选中', value: 1, num: +res.takeorders_infos.winner_num }, { name: '未选中', value: 0, num: +res.takeorders_infos.nowin_num }];
			} catch (e) {}
			data.loading = false;
		},
		// tab切换
		changeTab(item) {
			data.tabValue = item.value;
			data.searchParams.is_winner = item.value;
			if (data.publisher.yes) {
				publisher.bind();
			} else {
				merchant.bind();
			}
		},
		// 商家聊一聊
		async toIm() {
			await this.bind(true);
			if (!merchant.isLogin() || !merchant.isMerchant('im')) return;
			toIm(data.infos.publisher_mid, data.infos.publisher_nickname);
		},
		// 申请接单
		async getOrder() {
			await this.bind(true);
			if (!merchant.isLogin() || !merchant.isMerchant('order') || !merchant.isShowMobile() || !merchant.isNum()) return;
			const price = data.infos.price.split('-');
			uni.navigateTo({
				url: `/subpages/task/getorder/getorder?id=${data.taskid}&price=${price[0]}`,
				events: {
					acceptDataFromOpenedPage(res) {
						merchant.init();
					}
				}
			})
		},
		// 是否登录
		isLogin() {
			if (!store.getters.token) {
				navToCheckLogin();
				return false;
			}
			return true;
		},
		// 是否开通商家
		isMerchant(type) {
			if (data.merchant.info.is_merchant != 1) { //不是商户
				showModal({
					content: `成为行业大牛(商户)即可${type=='im'?'与甲方聊一聊':'申请接单'}`,
					confirmText: '入驻开通',
					confirm() {
						uni.navigateTo({
							url: '/subpages/user-merchant/open/open'
						})
					}
				})
				return false;
			} else { //是商户，检测商家的状态
				const merchantStatus = {
					normal: 1, //正常
					forbid: 2 //禁用
				}
				const merchantTrial = {
					review: 0, //审核中
					reviewSuccess: 1, //审核成功
					reviewFail: 2 //审核失败
				}
				if (+data.merchant.info.merchant_info.merchant_status == merchantStatus.forbid) {
					showModal({
						content: `由于您屡次违规，平台已收回您对本功能的使用权。感谢您的理解！如有疑问请联系QQ：${config.customer.qq_operate}`,
						confirmText: '我知道了',
						showCancel: false
					})
					return false;
				} else {
					switch (+data.merchant.info.merchant_info.merchant_trial) {
						case merchantTrial.review:
							showModal({
								content: `商户基本信息审核中，审核成功后即可${type=='im'?'与甲方聊一聊':'申请接单'}`,
								confirmText: '我知道了',
								showCancel: false
							})
							return false;
						case merchantTrial.reviewSuccess:
							break;
						case merchantTrial.reviewFail:
							showModal({
								content: `商户基本信息审核失败，修改并审核成功后即可${type=='im'?'与甲方聊一聊':'申请接单'}`,
								confirmText: '前往修改',
								confirm() {
									uni.navigateTo({
										url: `/subpages/user-merchant/set/base-info/base-info?trial=2`
									})
								}
							})
							return false;
					}
				}
			}
			return true;
		},
		// 判断手机是否对外展示
		isShowMobile() {
			if (data.merchant.info.isshowmobile != 1) {
				showModal({
					content: '需允许手机号对外展示，否则无法申请接单',
					confirmText: '一键允许',
					async confirm() {
						const res = await editPhoneNumber({ isshowmobile: 1 });
						data.merchant.info.isshowmobile = 1;
						merchant.getOrder();
					}
				})
				return false;
			}
			return true;
		},
		// 判断抢单次数
		isNum() {
			if (data.merchant.info.surplus <= 0) {
				uni.showToast({
					icon: 'none',
					title: `您今日已申请接单${data.merchant.info.sum}次，请明日再来~`
				})
				return false;
			}
			return true;
		},
		// 点击获取需求主的联系方式 
		async contact() {
			const res = await getPublisherMobile({ taskid: data.taskid });
			if (res.data.mobile) popupContactRef.value.open({ mobile: res.data.mobile }, 'mobile');
		}
	}
	// 接单大牛数据处理
	const takeOrders = computed(() => {
		const filter1 = dataList.value.filter(item => (+item.is_winner) == 1);
		const filter2 = dataList.value.filter(item => (+item.is_winner) == 0);
		let result = filter1.concat(filter2);
		result.forEach(item => {
			item.mobile = item.merchant_mobile;
			item.weixin = item.merchant_weixin;
		})
		return result;
	});
	// 处理选人按钮的状态
	const disabledPickConfirm = computed(() => {
		const filters = takeOrders.value.filter(item => item.checked);
		return !(filters.length > 0);
	});
	// 显示选人操作按钮
	const showPickHandle = computed(() => {
		const filters = dataList.value.filter(item => (+item.is_winner) > 0);
		const result = data.infos.check_status == TASK_STATUS.check.reviewSuccess && takeOrders.value.length && filters.length == 0 && ([TASK_STATUS.task.ongoing, TASK_STATUS.task.completed].indexOf(data.infos.task_status) > -1) && (TASK_STATUS.task.closed.indexOf(+data.infos.dealt_status) <
		0);
		return result;
	});
	// 判断是否显示更多提示
	const showMoreTip = computed(() => {
		const result = data.merchant.yes && (data.takeordersIinfos?.nowin_num + data.takeordersIinfos?.winner_num) > 4 && takeOrders.value.length >= 4;
		return result;
	});
	// 是否关闭了任务
	const showDetail = computed(() => {
		const result = (data.merchant.yes && data.infos && TASK_STATUS.task.closed.indexOf(+data.infos?.dealt_status) < 0) | data.publisher.yes;
		return result;
	});
	// 是否显示接单大牛
	const showTakeOrders = computed(() => {
		const result = data.tabList.length && data.infos.check_status == TASK_STATUS.check.reviewSuccess && TASK_STATUS.task.closed.indexOf(+data.infos?.dealt_status) < 0;
		return result;
	});
	// 审核状态
	function checkStatus(v) {
		switch (+v) {
			case TASK_STATUS.check.reviewing:
				return '审核中';
			case TASK_STATUS.check.reviewSuccess:
				return '审核成功';
			case TASK_STATUS.check.reviewFail:
				return '审核失败';
		}
	}
	// 状态筛选
	function taskStatus(v) {
		switch (+v) {
			case TASK_STATUS.task.ongoing:
				return '进行中';
			case TASK_STATUS.task.completed:
				return '已完成';
		}
	}
</script>
<style lang="scss">
	@import '@/common/css/base.scss';
	page {
		padding: 0 0 100rpx;
		padding-bottom: calc(constant(safe-area-inset-bottom) + 100rpx);
		padding-bottom: calc(env(safe-area-inset-bottom) + 100rpx);
		background-color: $bgColor;
	}
</style>
<style scoped lang="scss">
	@import '@/common/css/base.scss';
	$w:694rpx;
	@mixin common {
		width: $w;
		margin: 0 auto 28rpx;
		box-shadow: 0 0 10rpx 0 rgba(0, 0, 0, .08);
		border-radius: 18rpx;
		background-color: #fff;
	}
	.steps {
		height: 340rpx;
		padding: 20rpx 0;
		background-color: $color;
	}
	.infos {
		@include common;
		margin-top: -190rpx;
		padding: 32rpx 28rpx;
		.title {
			word-break: break-all;
			line-height: 54rpx;
			font-weight: 700;
			font-size: 36rpx;
			color: #222;
		}
		.tags {
			@include flex(row, flex-start);
			padding: 20rpx 0;
			.item {
				height: 44rpx;
				line-height: 44rpx;
				margin-right: 12rpx;
				padding: 0 16rpx;
				border-radius: 6rpx;
				font-size: 22rpx;
				&-task-status1 {
					background-color: #53A849;
					color: #fff;
				}
				&-task-status2 {
					background-color: #f5f5f5;
					color: #666;
				}
				&-check-status1 {
					background-color: #f5f5f5;
					color: #666;
				}
				&-check-status2 {
					background-color: #FFF5E5;
					color: $color;
				}
				&-check-status3 {
					background-color: #ff0000;
					color: #fff;
				}
			}
			.time {
				@include flex;
				background: #FFF5E5;
				color: $color;
				.icon {
					margin-right: 6rpx;
					font-size: 26rpx;
				}
			}
		}
		.price {
			padding: 0 0 20rpx;
			color: #ff0000;
			.unit {
				font-weight: 700;
				font-size: 30rpx;
			}
			.value {
				font-weight: 700;
				font-size: 40rpx;
			}
		}
		.date {
			font-size: 24rpx;
			color: #999;
		}
	}
	.detail .hd,
	.list .hd {
		@include flex(row, flex-start);
		padding: 34rpx 28rpx;
		font-size: 34rpx;
		color: #000;
		&::before {
			content: '';
			display: block;
			width: 8rpx;
			height: 32rpx;
			margin: 4rpx 16rpx 0 0;
			background: $color;
		}
	}
	.detail {
		@include common;
		padding: 0 28rpx 34rpx;
		.hd {
			padding: 34rpx 0;
		}
		.bd {
			line-height: 54rpx;
			word-break: break-all;
			font-size: 28rpx;
			color: #666;
		}
	}
	.list {
		@include common;
		.tab {
			padding: 0 28rpx 10rpx;
		}
		.order {
			padding: 0 0 30rpx;
		}
	}
	.foot {
		padding-bottom: 34rpx;
		.handle {
			text-align: center;
			.msg {
				font-size: 24rpx;
				color: #888;
			}
			.btn {
				display: inline-block;
				margin-left: 10rpx;
				font-size: 24rpx;
				color: $color;
			}
		}
	}
	.operate {
		@include flex(row, center);
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 2;
		padding-top: 14rpx;
		padding-bottom: calc(constant(safe-area-inset-bottom) + 14rpx);
		padding-bottom: calc(env(safe-area-inset-bottom) + 14rpx);
		background: #fff;
		.btn {
			width: 564rpx;
			height: 80rpx;
			line-height: 80rpx;
			margin: 0;
			border-radius: 40rpx;
			background: $color;
			text-align: center;
			font-size: 32rpx;
			color: #fff;
			&-one {
				width: 694rpx;
			}
			&-dis {
				background-color: #ccc;
			}
		}
		&-two {
			justify-content: flex-start;
			.btn.small {
				@include flex(column, center);
				width: 156rpx;
				height: 80rpx;
				background-color: transparent;
				font-size: 22rpx;
				color: #666;
				.icon {
					width: 42rpx;
					height: 40rpx;
					margin-bottom: 8rpx;
					font-size: 40rpx;
				}
				text {
					height: 24rpx;
					line-height: 24rpx;
				}
				&-font32 {
					font-size: 32rpx;
				}
			}
		}
	}
</style>
